package com.example.lhsama.security;

import com.example.lhsama.dao.UserMapper;
import com.example.lhsama.domain.Role;
import com.example.lhsama.domain.User;
import com.example.lhsama.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userService.selectByName(s);
        if (user == null || user.getDeleted() == 1){
            throw new UsernameNotFoundException("用户名不存在！");
        }
        if (user.getEnable()==0){
            throw new UsernameNotFoundException("用户已失效！");
        }

        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        Iterator<Role> iRole = userService.getRolesList(user.getId()).iterator();
        while (iRole.hasNext()){ // 添加查询到的角色信息
            authorities.add(new SimpleGrantedAuthority(iRole.next().getRoleName()));
        }
        user.setAuthorities(authorities);
        return user;
    }
}
